package xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : DuJiabao
 * @Date : 2021/1/23 10:14
 * @Project : java-web
 * @File : null.java
 * @Desc :
 */
public class Dom4jTest {
    @Test
    public void test() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read("./src/xml/book.xml");
        Element rootElement = document.getRootElement();
        List<Element> books = rootElement.elements("book");
        ArrayList<Book> booksArray = new ArrayList<>();

        for (Element book : books) {
            System.out.println(book.asXML());
//            获取孩子结点及文本
            Element nameElement = book.element("name");
            String name = nameElement.getText();
//            简便方式
            String author = book.elementText("author");
            int price = Integer.parseInt(book.elementText("price"));
//            获取属性值
            String id = book.attributeValue("ID");
            booksArray.add(new Book(id, name, author, price));
        }
        System.out.println(booksArray);

    }
}
